package top.oylan.manager.tools;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import top.oylan.manager.entity.Action;
import top.oylan.manager.entity.User;
import top.oylan.manager.service.UserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by A on 2019/2/11.
 */
public class AuthShiroRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    //  权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        User user = (User)principalCollection.getPrimaryPrincipal();

        List<String> perms = new ArrayList<>();

        // 获取用户权限

        List<Action> actions =  userService.findActionsByUserId(user.getId());

        if(actions != null){
            for(Action action:actions){
                perms.add(action.getActionCode());
            }
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }

    // 登录/授权
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        SimpleAuthenticationInfo info = null;
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String account = token.getUsername();

        User user = userService.selectUserByAccount(account);

        if(null == user){
            throw new UnknownAccountException();
        }else if(user.getType() != 1) {
            throw new DisabledAccountException();
        }else if(user.getStatus() != 1){
            throw new LockedAccountException();
        } else{
            ByteSource credentialsSalt = ByteSource.Util.bytes(account+"salt");
            info = new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,"shiroRealm");
        }
        return info;
    }
}
